package com.sixkey.task;

/**
 * ClassName: UpdateMeetStatus
 * Package: com.sixkey.task
 * Description:
 *
 * @Author: @weixueshi
 * @Create: 2023/10/11 - 12:48
 * @Version: v1.0
 */

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sixkey.constant.CommonConstant;
import com.sixkey.constant.RabbitMQConstant;
import com.sixkey.entity.Reservation;
import com.sixkey.rabbitmq.RabbitService;
import com.sixkey.service.IReservationService;
import com.sixkey.utils.JodaTimeUtils;
import com.sixkey.utils.TimeStringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 修改会议状态的定时任务
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class UpdateMeetStatusTask {

    private final IReservationService reservationService;

    private final RabbitService rabbitService;

    /**
     * 每分钟执行一次定时任务
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void UpdateMeetStatusTaskExecute() {
        log.info("修改会议状态定时任务开始..........");
        //把已结束的会议排除
        QueryWrapper<Reservation> wrapper = new QueryWrapper<Reservation>().eq("status", CommonConstant.RESERVATION_STATUS_1).or().eq("status", CommonConstant.RESERVATION_STATUS_2);
        List<Reservation> reservationList = reservationService.list(wrapper);
        reservationList.stream().forEach(item -> {
            //获取经处理过的字符串时间格式
            String beginTime = TimeStringUtils.getBeginTime(item.getBeginTime());
            String endTime = TimeStringUtils.getEndTime(item.getBeginTime());
            //将字符串转为LocalDateTime
            LocalDateTime beginLocalDateTime = LocalDateTime.parse(beginTime, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm"));
            LocalDateTime endLocalDateTime = LocalDateTime.parse(endTime, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm"));

            if(endLocalDateTime.isBefore(JodaTimeUtils.getCurrentDateTime())){
                //如果当前时间在会议结束时间后
                //将会议状态修改为已结束
                item.setStatus(CommonConstant.RESERVATION_STATUS_3);
                reservationService.updateById(item);
                //当会议结束后通过rabbitMQ去修改会议所使用的会议室状态为未预约
                log.info("MQ发送消息：{}",item.getRoomName());
                rabbitService.sendMessage(RabbitMQConstant.EXCHANGE_MEET_ROOM,RabbitMQConstant.ROUTING_MEET_ROOM,item.getRoomName());
            } else if (beginLocalDateTime.isBefore(JodaTimeUtils.getCurrentDateTime())) {
                //如果当前时间在会议开始时间后
                //将会议状态修改为进行中
                item.setStatus(CommonConstant.RESERVATION_STATUS_2);
                reservationService.updateById(item);
            }
        });
    }
}
